/*
 * Application.java July 2009
 *
 * Copyright (C) 2009, Quirino Zagarese <quirino@laszloitalia.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */
package org.eu4ria;

import java.util.Collection;
import java.util.Hashtable;
import java.util.Properties;

import org.eu4ria.core.AnnotationScanner;
import org.eu4ria.core.HashFunctions;
import org.eu4ria.core.ModulesInstantiator;

public class Application {

	private String name;

	private String hash;

	private Hashtable<String, AppModule> modules = new Hashtable<String, AppModule>();

	private Hashtable<String, String> hashBindings = new Hashtable<String, String>();

	private Hashtable<String, Object> modulesInstances = new Hashtable<String, Object>();

	private Properties jndiProperties = null;

	private ModulesInstantiator instantiator = null;

	public void addModule(AppModule module) {
		module.setDeclaringApp(this);
		modules.put(module.getJavaClass().getName(), module);
		String md5 = HashFunctions.getMD5(module.getJavaClass().getName());
		module.setHash(md5);
		hashBindings.put(md5, module
				.getJavaClass().getName());
	}

	public void instantiateModule(AppModule module) {
		Object instance = null;
		try {
			instance = instantiator.getInstanceOf(AnnotationScanner.getCtClass(module
					.getJavaClass().getName()));
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		module.setJavaObject(instance);
		modulesInstances.put(module.getJavaClass().getName(), instance);
	}

	public Collection<AppModule> getModules() {
		return modules.values();
	}

	public AppModule getModule(String name) {
		return modules.get(name);
	}

	public AppModule getModulesByHash(String hash) {
		return modules.get(hashBindings.get(hash));
	}

	public boolean containsModules() {
		return !modules.isEmpty();
	}

	public String getName() {
		return name;
	}

	public void setName(String path) {
		this.name = path;
	}


	public void setJndiProperties(Properties jndiProperties) {
		this.jndiProperties = jndiProperties;
		if (jndiProperties == null) {
			instantiator = new ModulesInstantiator();
		} else {
			instantiator = new ModulesInstantiator(jndiProperties);
		}
	}

	public Properties getJndiProperties() {
		return jndiProperties;
	}

	public String getHash() {
		return hash;
	}

	public void setHash(String hash) {
		this.hash = hash;
	}

}
